import Vuex from "vuex";

const setLocalCartList = (state) => {
  const { cartList } = state;
  const cartListString = JSON.stringify(cartList);
  localStorage.cartList = cartListString;
};

const getLocaCartList = () => {
  //cartList={
  //   "shopId": {
  //     "shopName": "",
  //     "productList": {
  //       "productId": {
  //         tabs: ["all", "seckill", "fruit"],
  //         shopId: "6162b97e226bf13191c1207f",
  //         name: "葡萄",
  //         imgUrl: "/images/product/grape.jpg",
  //         sales: 100,
  //         price: 33,
  //         oldPrice: 36,
  //         num: 2,
  //       },
  //     },
  //   },
  // }
  try {
    return JSON.parse(localStorage.cartList);
  } catch (e) {
    return {};
  }
};

export default Vuex.createStore({
  state: {
    cartList: getLocaCartList(),
    addressList: [],
  },
  mutations: {
    changeCartItemInfo(state, payload) {
      const { shopId, productId, productInfo } = payload;
      let shopInfo = state.cartList[shopId] || {
        shopName: "",
        productList: {},
      };
      let product = shopInfo.productList[productId];
      if (!product) {
        //商品不存在的情况下添加商品
        productInfo.count = 0;
        product = productInfo;
      }
      product.count = product.count + payload.num;
      if (payload.num > 0) {
        product.check = true; //添加新商品，初始状态为选中
      }
      if (product.count < 0) {
        product.count = 0;
      }
      shopInfo.productList[productId] = product;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state);
    },
    changeShopName(state, payload) {
      const { shopId, shopName } = payload;
      const shopInfo = state.cartList[shopId] || {
        shopName: "",
        productList: {},
      };
      shopInfo.shopName = shopName;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state);
    },
    changeCartItemChecked(state, payload) {
      const { shopId, productId } = payload;
      const product = state.cartList[shopId].productList[productId];
      product.check = !product.check;
      setLocalCartList(state);
    },
    cleanCartProducts(state, payload) {
      const { shopId } = payload;
      state.cartList[shopId].productList = {};
      setLocalCartList(state);
    },
    // 改变选中状态
    setCartItemsChecked(state, payload) {
      const { shopId } = payload;
      const products = state.cartList[shopId].productList;
      if (products) {
        for (let key in products) {
          const product = products[key];
          product.check = true;
        }
      }
      setLocalCartList(state);
    },
    clearCartData(state, shopId) {
      state.cartList[shopId].productList = {};
    },
    changeAddressList(state, addressList) {
      state.addressList.splice(0, state.addressList.length, ...addressList);
    },
  },
});
